package com.example.dnfgamercommunitybackend.service.impl;

import com.example.dnfgamercommunitybackend.dao.CommentDao;
import com.example.dnfgamercommunitybackend.entity.Comment;
import com.example.dnfgamercommunitybackend.entity.ResponseResult;
import com.example.dnfgamercommunitybackend.service.CommentService;
import com.example.dnfgamercommunitybackend.util.DfaUtil;
import com.example.dnfgamercommunitybackend.util.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    private CommentDao commentDao;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private DfaUtil dfaUtil;
    @Override
    public String addComment(Comment comment,String authorization) {
        if (!StringUtils.hasText(comment.getContent())){
            return ResponseResult.failureStringResult(504,"评论失败，请填写评论内容");
        }else {
            //过滤评论，检查评论内容是否合规
            if (dfaUtil.textFilter(comment.getContent())){
                comment.setAccountId(Integer.parseInt(jwtUtil.getUserIdFromToken(authorization)));
                if (commentDao.addComment(comment) > 0){
                    return ResponseResult.successStringResult("评论成功");
                }
            }else {
                return ResponseResult.failureStringResult(505,"评论内容不合规，请修改");
            }
            return ResponseResult.failureStringResult("评论失败，服务器故障");
        }
    }

    @Override
    public String deleteComment(int commentId,String authorization) {
        Comment comment = new Comment();
        comment.setId(commentId);
        comment.setAccountId(Integer.parseInt(jwtUtil.getUserIdFromToken(authorization)));
        if (commentDao.deleteComment(comment) > 0){
            return ResponseResult.successStringResult("评论删除成功");
        }else{
            return ResponseResult.failureStringResult(504,"评论删除失败");
        }
    }

    @Override
    public List<Comment> getAllComment(int articleId) {
        return commentDao.getAllComment(articleId);
    }


    @Override
    public List<Comment> getAllCommentByArticleId(int articleId) {
        List<Comment> parentComments = commentDao.getCommentByArticleId(articleId);
        return getReplyComments(parentComments);
    }

    //获取子评论
    private List<Comment> getReplyComments(int parentCommentId){
        return commentDao.getReplyComments(parentCommentId);
    }

    private List<Comment> getReplyComments(List<Comment> parentComments){
        if (parentComments.isEmpty()){
            return null;
        }
        parentComments
                .forEach(parentComment -> {
                    List<Comment> replyComments = getReplyComments(parentComment.getId());
                    parentComment.setComments(getReplyComments(replyComments));
                });
        return parentComments;
    }
}
